package com.h5lib.nchuoffice.app.action;

import java.io.IOException;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.h5lib.nchuoffice.CacheManager;
import com.h5lib.nchuoffice.NchuOfficeUtils;
import com.h5lib.nchuoffice.NchuSqlException;
import com.h5lib.nchuoffice.app.cfg.Config;
import com.h5lib.nchuoffice.model.UserInfo;
import com.h5lib.server.ModelMap;
import com.h5lib.server.annotation.Controller;
import com.h5lib.server.annotation.RequestMapping;

import fi.iki.elonen.NanoHTTPD.IHTTPSession;
import fi.iki.elonen.NanoHTTPD.Response;
import fi.iki.elonen.NanoHTTPD.Response.Status;

@Controller
public class GradeAction {
	
	/**
	 * 成绩查询
	 * @param session
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value="/grade.html")
	public String grade(IHTTPSession session, Response response ,ModelMap modelMap){
		return "/ui/grade.html";
	}
	
	
	@RequestMapping(value="/doGrade")
	public Response doGrade(IHTTPSession session, Response response ,ModelMap modelMap){
		Object userInfo = CacheManager.getCache(Config._CACHE_USERINFO);
		modelMap.put("userInfo", userInfo);
		try {
			Map<String, Object> grades = null;
			String cacheKey = Config._CACHE_GRADE+"_"+((UserInfo)userInfo).getUserNo();
			if(CacheManager.getCache(cacheKey) == null){
				grades = NchuOfficeUtils.getGrades();
				CacheManager.addCache(cacheKey, grades);
			}
			modelMap.put("err", "0");
			modelMap.put("grades", CacheManager.getCache(cacheKey));
		} 
		catch(IOException e){
			e.printStackTrace();
			modelMap.put("msg", "网络异常");
			modelMap.put("err", "-1");
		}
		catch (NchuSqlException e) {
			e.printStackTrace();
			modelMap.put("msg", "服务器数据库异常");
			modelMap.put("err", "-1");
		}
		catch (Exception e) {
			e.printStackTrace();
			modelMap.put("msg", "服务器异常");
			modelMap.put("err", "-1");
		}
		return new Response(Status.OK, "text/plain", JSON.toJSONString(modelMap.getMap()));
	}
}